#include "Keyboard.h"

Keyboard::Keyboard()
{
	dInput = NULL;
	dInputDevice = NULL;
}
Keyboard::~Keyboard()
{
	if(dInputDevice)
	{
		dInputDevice -> Unacquire();
		dInputDevice -> Release();
	}
	if(dInput)
	{
		dInput -> Release();
	}
	_kb = NULL;
}

Keyboard *Keyboard::_kb = NULL;

Keyboard *Keyboard::GetInstance()
{
	if(_kb==NULL)
	{
		_kb=new Keyboard();
	}
	return _kb;
}
bool Keyboard::Initialize(HWND hWnd, HINSTANCE hInstance)
{
	if(!SUCCEEDED(  DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&dInput, NULL )))
		return false;

	if(!SUCCEEDED(dInput->CreateDevice(GUID_SysKeyboard, &dInputDevice, NULL)))
		return false;

	if(!SUCCEEDED( dInputDevice->SetDataFormat(&c_dfDIKeyboard)))
		return false;

	if(!SUCCEEDED( dInputDevice->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
		return false;

	DIPROPDWORD dipdw;
	dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
	dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
	dipdw.diph.dwObj        = 0;
	dipdw.diph.dwHow        = DIPH_DEVICE;
	dipdw.dwData            = 1024; // Arbitary buffer size

	if(!SUCCEEDED(dInputDevice->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph)))
		return false;

	Acquire();
	return true;
}
bool Keyboard::Acquire()
{
	if(!SUCCEEDED(dInputDevice->Acquire()))
		return false;
	return true;
}
void Keyboard::GetDeviceState()
{
	// Collect all key states first
	dInputDevice->GetDeviceState(sizeof(KeyStates), KeyStates);
}


int Keyboard::IsKeyDown(int KeyCode)
{
	return (KeyStates[KeyCode] & 0x80) > 0;
}

